<?php
require_once("libs/general_inc.php");

class Coupon extends Controller {

    function __construct() {
        parent::__construct();
    }
    /*function chk_code_exists($cp_code){
             authentication();
             $sql = new sql();
             $sql->connect(); 
             $lastcouponquery = "select cp_code from tbl_coupon where cp_code =". $cp_code;
             $lastCoupon = $sql->fetchSimpleData($lastcouponquery);
             if( count($lastCoupon) != 0){
                $cp_code =  rand(10000, 100000);
                $this->chk_code_exists($cp_code);
             }else{
                 echo 'in';
                 echo $cp_code;
                 return $cp_code;
             }
        }
       
      */ 
    
    
     public static function generatePassword($length = 6, $level = 2) {
       
        list($usec, $sec) = explode(' ', microtime());
        srand((float) $sec + ((float) $usec * 100000));

        $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
        $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";
        $validchars[4] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $password = "";
        $counter = 0;

        while ($counter < $length) {
            $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level]) - 1), 1);

            // All character must be different
            if (!strstr($password, $actChar)) {
                $password .= $actChar;
                $counter++;
            }
        }
       // echo $password;
         return strtoupper($password);
    }

    
    public function isValidPrice($number) {
        return preg_match('/^[0-9]+(?:\.[0-9]+)?$/im', $number);
    }
    
    public function isValidNum($number) {
        return preg_match('/^[0-9]+$/', $number);
    }
    
    
      function index() {
        $sql = new sql();
        $sql->connect();
        $errorArray = Array();
        $cp_expiry_date = '';
        $cp_code = '';
        $cp_price = '';
        $cp_used_time = '';
        $no_limit_used = '';
        $cp_type = '';
        $cp_cat_id = '';
        $cp_prd_id = '';
        $cp_order_price = '';
        $cp_apply_discount = '';
        $cp_startdate = '';
        $cp_expirystatus = '';
        $categoryData = array();
        $productData = array();
        authentication();
        $getPage = getPage();
        $this->view->getPage = $getPage[0];
         $GENOBJ = new generalFunction();
        $dateTime = DateTime();
        $this->view->template = $sql->fetchAll("template", array("1" => '1'));
        
        //$cp_code = '88435';//rand(10000, 100000);
        
       /// echo $this->chk_code_exists($cp_code);
       /// exit;
        $this->view->cp_code = '';
        if (GET('action') == 'random_numb') {
           echo $this->generatePassword();
           exit;
        }
        
        if (isset($_POST['delete'])) {
            for ($i = 0; $i < count($_POST['cp_id']); $i++) {
                
                $arraydata = array(
                    "cp_status" => 2,
                );
                $update = $sql->update('tbl_coupon', $arraydata, array("cp_id" => $_POST['cp_id'][$i]));
            }
            if ($update) {
                header("Location: " . URL . "coupon/?action=view&reply=CouponDeleted");
            } else {
                header("Location: " . URL . "coupon/?action=view&reply=CouponError");
            }
        }

        if (GET('action') == 'add') {
            
            $categoryData = $sql->fetchAll('tbl_category', array("cat_status !" => 2));
            $productData = $sql->fetchAll('tbl_product', array("prd_status !" => 2));
            
            if (isset($_POST['submit'])) {
                
                if($_POST['cp_code'] != ''){
                    $lastcouponquery = "select cp_code from tbl_coupon where cp_code ='". $_POST['cp_code']."'";
                    $lastCoupon = $sql->fetchSimpleData($lastcouponquery);
                }
                
                $cp_expiry_date = $_POST['cp_expiry_date'];
                $cp_code = trim($_POST['cp_code']);
                $cp_price = $_POST['cp_price'];
                
                
                $cp_used_time = $_POST['cp_used_time'];
                if(array_key_exists('no_limit_used', $_POST)){
                    $no_limit_used = $_POST['no_limit_used'];
                }
                
                $cp_type = $_POST['cp_type'];
                $cp_cat_id = $_POST['cp_cat_id'];
                $cp_prd_id = $_POST['cp_prd_id'];
                $cp_order_price = $_POST['cp_order_price'];
                if($cp_type != 'all_order' && $cp_type != 'orders_over' ){
                    $cp_apply_discount = $_POST['cp_apply_discount'];
                }else{
                    $cp_apply_discount = '';
                }
                $cp_startdate = $_POST['cp_startdate'];
                
                if(array_key_exists('cp_expirystatus', $_POST)){
                    $cp_expirystatus = $_POST['cp_expirystatus'];
                }
                                
                if($cp_code == ''){
                    $errorArray[] = 'Please enter code';
                }
                if($cp_code != '' && count($lastCoupon) > 0 && trim($cp_code) == trim($lastCoupon[0]['cp_code'])){
                    $errorArray[] = 'Please create new code.this code already exists';
                }
                if($cp_used_time == '' &&  $no_limit_used == ''){
                    $errorArray[] = 'Please enter limit of coupon';
                }
                if($cp_used_time != '' &&  $this->isValidNum($cp_used_time) == 0){
                    $errorArray[] = 'Please enter only integer';
                }
                
                if($cp_type == 'collection' &&  $cp_cat_id == ''){
                    $errorArray[] = 'Please select category';
                }
                if($cp_type == 'specific_product' &&  $cp_prd_id == ''){
                    $errorArray[] = 'Please select product';
                } 
                if($cp_type == 'orders_over' &&  $cp_order_price == ''){
                    $errorArray[] = 'Please enter order price';
                } 
                if($cp_price == ''){
                    $errorArray[] = 'Please enter price';
                }
                if($cp_price != '' && $this->isValidPrice($cp_price) == 0){
                    $errorArray[] = 'Please enter valid price';
                }
                if($cp_startdate == ''){
                    $errorArray[] = 'Please select start date';
                }
				/*
                if(strtotime($cp_startdate) < strtotime(date('Y-m-d'))){
                    $errorArray[] = 'Please enter valid start date';
                }*/
                if($cp_expirystatus== '' &&  $cp_expiry_date == ''){
                    $errorArray[] = 'Please select expiry date';
                }
               /* if(strtotime($cp_expiry_date) <= strtotime(date('Y-m-d'))){
                    $errorArray[] = 'Please enter valid expiry date';
                }*/
                if($cp_expirystatus== '' &&  strtotime($cp_expiry_date) <= strtotime($cp_startdate)){
                    $errorArray[] = 'Please enter valid expiry date';
                }
                
                if(count($errorArray) > 0){
                }else{
                    $arraydata = array("cp_code" => $cp_code,
                    'cp_used_time' => $cp_used_time,
                    'no_limit_used' => $no_limit_used,
                    'cp_type' => $cp_type,
                    'cp_cat_id' => $cp_cat_id,
                    'cp_prd_id' => $cp_prd_id,
                    'cp_order_price' => $cp_order_price,
                    'cp_apply_discount' => $cp_apply_discount,
                    'cp_startdate' => $cp_startdate,
                    'cp_expirystatus' => $cp_expirystatus,
                    'cp_expiry_date' => $_POST['cp_expiry_date'],
                    'cp_status' => 1,
                    'cp_price' =>$_POST['cp_price'],
                    'cp_createdate' => date('Y-m-d h:i:s'),
                    'cp_updatedate' => date('Y-m-d h:i:s'),
                    'LastModifyBy' => base64_decode($_COOKIE['login_user_uid']),
                    );
                    
                    $filterArray = Array("TrimElement", "htmlEntity");  
                    $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                
                    $insert = $sql->insert('tbl_coupon', $filterElements);
                  
                    
                    if ($insert) {
                        header("Location: " . URL . "coupon/?action=view&reply=CouponCreated");
                    } else {
                        header("Location: " . URL . "coupon/?action=view&reply=CouponError");
                    }
                }
                
                
                 
            }   
            $this->view->cp_used_time = $cp_used_time;
            $this->view->no_limit_used = $no_limit_used;
            $this->view->cp_type = $cp_type;
            $this->view->cp_cat_id = $cp_cat_id;
            $this->view->cp_prd_id = $cp_prd_id;
            $this->view->cp_order_price = $cp_order_price;
            $this->view->cp_startdate = $cp_startdate;
            $this->view->cp_apply_discount = $cp_apply_discount;
            $this->view->cp_expirystatus = $cp_expirystatus;
            $this->view->cp_price = $cp_price;
            $this->view->cp_code = $cp_code;
            $this->view->cp_expiry_date = $cp_expiry_date;
            $this->view->ErrorMessage = $errorArray;     
        }

        if (isset($_POST['submit']) and isset($_POST['editUid'])) {
                
            $categoryData = $sql->fetchAll('tbl_category', array("cat_status !" => 2));
            $productData = $sql->fetchAll('tbl_product', array("prd_status !" => 2));
            
            
                $cp_expiry_date = $_POST['cp_expiry_date'];
                $cp_price = $_POST['cp_price'];
                
                $cp_used_time = $_POST['cp_used_time'];
                if(array_key_exists('no_limit_used', $_POST)){
                    $no_limit_used = $_POST['no_limit_used'];
                }
                
                $cp_type = $_POST['cp_type'];
                $cp_cat_id = $_POST['cp_cat_id'];
                $cp_prd_id = $_POST['cp_prd_id'];
                $cp_order_price = $_POST['cp_order_price'];
               if($cp_type != 'all_order' && $cp_type != 'orders_over' ){
                    $cp_apply_discount = $_POST['cp_apply_discount'];
                }else{
                    $cp_apply_discount = '';
                }$cp_startdate = $_POST['cp_startdate'];
                
                if(array_key_exists('cp_expirystatus', $_POST)){
                    $cp_expirystatus = $_POST['cp_expirystatus'];
                }
                                
               
                if($cp_used_time == '' &&  $no_limit_used == ''){
                    $errorArray[] = 'Please enter limit of coupon';
                }
                if($cp_used_time != '' &&  $this->isValidNum($cp_used_time) == 0){
                    $errorArray[] = 'Please enter only integer';
                }
                
                if($cp_type == 'collection' &&  $cp_cat_id == ''){
                    $errorArray[] = 'Please select category';
                }
                if($cp_type == 'specific_product' &&  $cp_prd_id == ''){
                    $errorArray[] = 'Please select product';
                } 
                if($cp_type == 'orders_over' &&  $cp_order_price == ''){
                    $errorArray[] = 'Please enter order price';
                } 
                if($cp_price == ''){
                    $errorArray[] = 'Please enter price';
                }
                if($cp_price != '' && $this->isValidPrice($cp_price) == 0){
                    $errorArray[] = 'Please enter valid price';
                }
                if($cp_startdate == ''){
                    $errorArray[] = 'Please select start date';
                }
				/*
                if(strtotime($cp_startdate) <= strtotime(date('Y-m-d'))){
                    $errorArray[] = 'Please enter valid start date';
                }*/
                if($cp_expirystatus== '' &&  $cp_expiry_date == ''){
                    $errorArray[] = 'Please select expiry date';
                }
               /* if(strtotime($cp_expiry_date) <= strtotime(date('Y-m-d'))){
                    $errorArray[] = 'Please enter valid expiry date';
                }*/
                if($cp_expirystatus== '' &&  strtotime($cp_expiry_date) <= strtotime($cp_startdate)){
                    $errorArray[] = 'Please enter valid expiry date';
                }
                if(count($errorArray) > 0){
                }else{
                    /*
                    $arraydata = array("cp_code" => $_POST['cp_code'],
                        "cp_expiry_date" => $_POST['cp_expiry_date'],
                        "cp_status" => $_POST['cp_status'],
                        "cp_price" =>$_POST['cp_price'],
                        //"cp_createdate" => date('Y-m-d h:i:s'),
                        "cp_updatedate" => date('Y-m-d h:i:s'),
                        "LastModifyBy" => base64_decode($_COOKIE['login_user_uid']),
                    );*/
                    
                    $arraydata = array(
                    'cp_used_time' => $cp_used_time,
                    'no_limit_used' => $no_limit_used,
                    'cp_type' => $cp_type,
                    'cp_cat_id' => $cp_cat_id,
                    'cp_prd_id' => $cp_prd_id,
                    'cp_order_price' => $cp_order_price,
                    'cp_apply_discount' => $cp_apply_discount,
                    'cp_startdate' => $cp_startdate,
                    'cp_expirystatus' => $cp_expirystatus,
                    'cp_expiry_date' => $_POST['cp_expiry_date'],
                    'cp_status' => 1,
                    'cp_price' =>$_POST['cp_price'],
                    'cp_updatedate' => date('Y-m-d h:i:s'),
                    'LastModifyBy' => base64_decode($_COOKIE['login_user_uid']),
                    );
                    
                    $filterArray = Array("TrimElement", "htmlEntity");  
                    $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                     //$update=$sql->update('page',array("permalink"=>$permalink),array("uid"=>$_POST['editUid']));
                    $update = $sql->update('tbl_coupon', $filterElements, array("cp_id" => $_POST['editUid']));
                    if ($update) {
                        header("Location: " . URL . "coupon/?action=view&reply=CouponUpdated");
                    } else {
                        header("Location: " . URL . "coupon/?action=view&reply=CouponError");
                    }
            
                }
            $this->view->cp_used_time = $cp_used_time;
            $this->view->no_limit_used = $no_limit_used;
            $this->view->cp_type = $cp_type;
            $this->view->cp_cat_id = $cp_cat_id;
            $this->view->cp_prd_id = $cp_prd_id;
            $this->view->cp_order_price = $cp_order_price;
            $this->view->cp_startdate = $cp_startdate;
            $this->view->cp_apply_discount = $cp_apply_discount;
            $this->view->cp_expirystatus = $cp_expirystatus;
            
                $this->view->cp_price = $cp_price;
                $this->view->cp_code = $cp_code;
                $this->view->cp_expiry_date = $cp_expiry_date;
              
           
        }



        if (GET('action') == 'view') {
            $page = (int) (GET("page") ? GET("page") : 1 );
            if (GET('search')) {
                $statement = "tbl_coupon where cp_status!=2 and  cp_code like '%" . GET('q') . "%' order by cp_id desc";
                $this->view->oldData = "action=" . GET('action') . "&q=" . GET('q') . "search=" . GET('q');
            } else {
                $statement = "tbl_coupon where cp_status!=2 order by cp_id desc";
                $this->view->oldData = "action=" . GET('action');
            }
            $limit = 50;
            $this->view->statement = $statement;
            $this->view->limit = $limit;
            $this->view->page = $page;
            $this->view->PagingNationFetch = $sql->PagingNationFetch($statement, $page, $limit);
        } 
        else if (GET('action') == 'edit' && isset($_POST['submit']) and isset($_POST['editUid'])) {
            $this->view->editrow = $sql->fetch("tbl_coupon", array("cp_id" => GET('editUid')));
            $this->view->cp_code = $this->view->editrow['cp_code'];
            $this->view->cp_price = $_POST['cp_price'];
            $this->view->cp_expiry_date = $_POST['cp_expiry_date'];
            $this->view->ErrorMessage = $errorArray;  
            

        }else if (GET('action') == 'edit' ) {
            $categoryData = $sql->fetchAll('tbl_category', array("cat_status !" => 2));
            $productData = $sql->fetchAll('tbl_product', array("prd_status !" => 2));
            
            
            $this->view->editrow = $sql->fetch("tbl_coupon", array("cp_id" => GET('editUid')));
            $this->view->ErrorMessage = $errorArray;  
            
            $this->view->cp_used_time = $this->view->editrow['cp_used_time'];
            $this->view->no_limit_used = $this->view->editrow['no_limit_used'];
            $this->view->cp_type = $this->view->editrow['cp_type'];
            $this->view->cp_cat_id = $this->view->editrow['cp_cat_id'];
            $this->view->cp_prd_id = $this->view->editrow['cp_prd_id'];
            $this->view->cp_order_price = $this->view->editrow['cp_order_price'];
            $this->view->cp_startdate = $this->view->editrow['cp_startdate'];
            $this->view->cp_apply_discount = $this->view->editrow['cp_apply_discount'];
            $this->view->cp_expirystatus = $this->view->editrow['cp_expirystatus'];
            
            
            $this->view->cp_code = $this->view->editrow['cp_code'];
            $this->view->cp_price = $this->view->editrow['cp_price'];
            $this->view->cp_expiry_date = $this->view->editrow['cp_expiry_date'];
            

        }


        if (GET('reply')) {
            $this->view->noti = msg(GET('reply'));
        }

        if (checkPermission('premission_coupon')) {
            $this->view->categoryData = $categoryData;
            $this->view->productData = $productData;
            $this->view->render('coupon');
        } else {
            $this->view->render('permission_denied');
        }
    }

}
